package jt.android.platformania.api;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import jt.android.platformania.world.Level;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class FileManager implements Handler.Callback
{
	// Members
	private Handler handler;
	private String tag;
	private Context context;
	private FileOutputStream fos;
	private FileInputStream fis;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	
	// Signals
	public static final int SIG_SAVE_LEVEL	= 0;
	public static final int SIG_LOAD_LEVEL  = 1;
	
	public FileManager(Context context)
	{
		// Initialize
		handler = new Handler(this);
		tag = "FileManager";
		this.context = context;
		fos = null;
		fis = null;
		oos = null;
		ois = null;
	}
	
	//sets the file output stream
	public void setFOS(String filename)
	{
		try {
			fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	//sets the file input stream
	public void setFIS(String filename)
	{
		try {
			fis = new FileInputStream(filename);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public boolean handleMessage(Message msg) 
	{
		// Switch on message signal
		switch(msg.what)
		{
			case SIG_SAVE_LEVEL:
				Level l = (Level) msg.obj; //casting to Level, good form?
				setFOS(new String("level" + l.getID()));
				try {
					oos = new ObjectOutputStream(fos);
					oos.writeObject(l);
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			case SIG_LOAD_LEVEL:
				setFIS("level" + msg.arg1);
				/*try {
					ois = new ObjectInputStream(fis);
					
					//send this level object somewhere
					Level l2 = (Level) ois.readObject();
					System.out.println("the current level is " + l2.getID());
					
				} catch (IOException e) {
					e.printStackTrace();
				}
				catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
				break;				
			default:
				break;
		}
		return false;
	}
	
	public Handler getHandler()
	{
		return handler;
	}
};
